package com.qf.smsplatform.interceptor;
/*2021/10/28*/

import com.fasterxml.jackson.databind.ObjectMapper;
import com.qf.smsplatform.constans.ResultCode;
import com.qf.smsplatform.dto.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @YuTao
 */
//@Component
public class LoginInterceptor implements HandlerInterceptor {

    private ObjectMapper objectMapper;
    @Autowired
    public void setObjectMapper(ObjectMapper objectMapper) {
        this.objectMapper = objectMapper;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Boolean loginUser=request.getSession().getAttribute("user")!=null;
            if (!loginUser){
            R r = R.setError(ResultCode.NOT_LOGIN, "用户没有登录", null);
            response.setContentType("application/jackson;charset=utf-8");
            response.getWriter().write(objectMapper.writeValueAsString(r));
        }
        return loginUser;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
